﻿using System;
using System.Net.Mail;
using System.IO;

namespace DotNetNexusSpam.SpamFilter
{
    class SpamDeleteFilter : FilterBase
    {
        public SpamDeleteFilter(CDOMessageWrapper email, string startupPath)
            : base(email, startupPath)
        {
            base.Name = "DeleteSpam";
        }

        public override void Fire()
        {
            base.ActionToTake = FilterAction.PROCESS_NORMALLY;
            base.IsSpam = false;

            foreach (string tag in _spamDeleteWords) {
                if (Email.CDOMessage.TextBody.Contains(tag) ||
                    Email.CDOMessage.HTMLBody.Contains(tag) ||
                    Email.CDOMessage.Subject.Contains(tag) ||
                    Email.CDOMessage.From.Contains(tag) ||
                    Email.CDOMessage.To.Contains(tag)) 
                {
                    base.ActionToTake = FilterAction.DELETE_EMAIL;
                    base.IsSpam = true;
                    break;
                }
            }
        }

        /// <summary>
        /// Load all words that the engine uses to definitively delete spam.
        /// </summary>
        private const string SPAM_DELETE = "spamDelete.txt";
        private string[] _spamDeleteWords;
        public override void LoadConfiguration()
        {
            string settingsPath = base.StartupPath + "config\\" + SPAM_DELETE;
            if (File.Exists(settingsPath))
            {
                string spamDeleteContent = "";
                using (StreamReader settingsReader = new StreamReader(settingsPath))
                {
                    spamDeleteContent = settingsReader.ReadToEnd();
                }
                _spamDeleteWords = spamDeleteContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                _log.Debug("SpamDelete tags file was loaded succesfully.");
            }
            else
            {
                _log.Warn("SpamDelete tags file could not be loaded from " + settingsPath);
            }
        }

    }
}
